package com.uvnos4j.matilda.commons.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.uvnos4j.matilda.commons.dto.PageParam;
import com.uvnos4j.matilda.commons.dto.QueryParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;

/**
 * 请求处理工具类
 * <p>
 * Description:请求处理工具类
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @see com.uvnos4j.matilda.commons.utils
 * @since 2020-08-31 22:38:42
 */
public class RequestUtil {

    /**
     * 获取 HttpServletRequest
     *
     * @return request
     */
    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        assert requestAttributes != null;
        return requestAttributes.getRequest();
    }

    /**
     * 判断请求是否为 Ajax 请求
     *
     * @return true/false
     */
    public static boolean isAjax() {
        return "XMLHttpRequest".equals(getHttpServletRequest().getHeader("X-Requested-With"));
    }

    /**
     * 获取查询条件
     *
     * @return param
     */
    public static QueryParam getQueryParam() {
        QueryParam param = new QueryParam();
        HttpServletRequest request = getHttpServletRequest();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            String value = "";
            if (values == null || values.length == 0) {
                //
            } else if (values.length == 1) {
                value = values[0];
            } else {
                for (String s : values) {
                    value += s + ',';
                }
                value = value.substring(value.length() - 1);
            }
            param.put(key, value);
        }
        return param;
    }

    /**
     * 根据当前页码和每页条数组装分页信息
     *
     * @param pageNoParameter   当前页码Parameter
     * @param pageSizeParameter 每页条数Parameter
     * @return 分页信息
     */
    public static PageParam packagePageParamByNumAndSize(String pageNoParameter, String pageSizeParameter) {
        HttpServletRequest request = getHttpServletRequest();
        int pageNo = Convert.toInt(request.getParameter(pageNoParameter), 1);
        int pageSize = Convert.toInt(request.getParameter(pageSizeParameter), Integer.MAX_VALUE);
        return PageParam.buildByNumAndSize(pageNo, pageSize);
    }

    /**
     * 组装排序信息
     *
     * @param sortParameter   排序字段Parameter
     * @param orderParameter  排序方式Parameter
     * @param underlineToCase 是否要对排序字段将下划线转换为驼峰
     * @return 排序信息
     */
    public static String packageOrderBy(String sortParameter, String orderParameter, boolean underlineToCase) {
        String sortAndOrder = "";

        HttpServletRequest request = getHttpServletRequest();
        String sort = request.getParameter(sortParameter);
        String order = request.getParameter(orderParameter);
        return getString(sortAndOrder, sort, order, underlineToCase);
    }

    public static String getString(String sortAndOrder, String sort, String order, boolean underlineToCase) {
        if (StrUtil.isNotBlank(sort) && StrUtil.isNotBlank(order)) {
            String[] sorts = sort.split(",");
            String[] orders = order.split(",");

            for (int i = 0, len = sorts.length; i < len; i++) {
                String s = sorts[i];
                if (underlineToCase) {
                    s = StrUtil.toUnderlineCase(sorts[i]);
                }
                sortAndOrder += s + " " + orders[i] + ",";
            }
            sortAndOrder = sortAndOrder.substring(0, sortAndOrder.length() - 1);
        }
        Console.log("排序信息：[{}]。", sortAndOrder);
        return sortAndOrder;
    }

    /**
     * 获取 URL 地址在文件系统的绝对路径
     *
     * @param path 路径
     * @return 绝对路径
     */
    public static String getRealPath(String path) {
        return getHttpServletRequest().getServletContext().getRealPath(path);
    }

    /**
     * 获取 下载路径 地址在文件系统的绝对路径
     *
     * @return 绝对路径
     */
    public static String getDownloadPath() {
        String downloadPath = getRealPath("/download/");
        File dir = new File(downloadPath);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException("目录创建失败:" + dir.toString());
            }
        }
        return downloadPath;
    }

}